package com.horoscope.astrology.zodiac.signs.free.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.DialogInterface
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.ArrayMap
import android.util.Log
import android.view.View
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.bean.CityInfo
import com.horoscope.astrology.zodiac.signs.free.bean.UserBean
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.SysUtils
import com.horoscope.astrology.zodiac.signs.free.utils.dialog.DialogSelectBornTime
import com.horoscope.astrology.zodiac.signs.free.utils.dialog.DialogSelectCity
import com.horoscope.astrology.zodiac.signs.free.utils.dialog.DialogSelectGenderOrStatus
import com.horoscope.astrology.zodiac.signs.free.view.DatePicker
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_input_profile_new.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.io.IOException
import java.util.*

class InputProfileActivity : BaseActivity(), View.OnClickListener {

    private var mDialogGenderOrStatus: DialogSelectGenderOrStatus? = null
    private var mDialogCity: DialogSelectCity? = null
    private var mDialogTime: DialogSelectBornTime? = null
    private var datePicker: DatePicker? = null
    private var birthday: String? = null
    private var city: String? = null

    private var tempUserBean = UserBean()
    private var mUserBean: UserBean? = null
    private var map = ArrayMap<String, Any>()

    private var fromToThis: String? = null
    private var tag = 1
    private var job: Job? = null
    private lateinit var fusedLocationClient: FusedLocationProviderClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_input_profile_new)
        intent?.let {
            if (it.getBooleanExtra("Alarm", false)) {
                activityShowAd("Push_Name")
            }
        }
        initTitleBar(
            this@InputProfileActivity,
            R.id.btn_back_edit_name,
            R.id.text_view_back_title,
            getString(R.string.label_profile)
        )
        mUserBean = AppSettingManager.readObject("user_info")
        getLocationForPermission()
        initViewText()
        initListeners()
        FlurryEventUtil.putDataToEvent(EventType.TYPE_BIRTH_CHAT_PROFILE_SHOW, null, null)
    }

    // 控件Hint初始化
    private fun initViewText() {
        if (mUserBean == null) {
            mUserBean = UserBean()
            tv_birthday!!.hint = "Choose birthday"
        } else {
            tv_birthday.text = mUserBean!!.birthday
        }

        fromToThis = intent.getStringExtra("fromContext")
        // 如果是从AstrologyFragment进入
        if (fromToThis.equals("AstrologyFragment")) {
            edit_name.setText(mUserBean!!.name)
            tv_gender_1.text = mUserBean!!.gender
            tv_birthday.text = mUserBean!!.birthday
            tv_time.text = mUserBean!!.bornTime
            tv_born_place.text = mUserBean!!.bornPlace
            tv_status.text = mUserBean!!.marial_status
        } else {
            tv_birthday.text = ""
            tv_birthday!!.hint = "Choose birthday"
            tv_gender_1.text = "Male"
        }
    }

    private fun initListeners() {
        edit_name.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                buttonIsEnable()
            }
        })
        tv_gender_1.setOnClickListener(this)
        tv_birthday.setOnClickListener(this)
        tv_time.setOnClickListener(this)
        tv_born_place.setOnClickListener(this)
        tv_status.setOnClickListener(this)
        tv_result?.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        if (!SysUtils.isFastClick()) {
            when (v?.id) {
                R.id.tv_gender_1 -> {
                    tag = 1
                    mDialogGenderOrStatus = DialogSelectGenderOrStatus(tag, "InputProfileActivity")
                    dialogShow(mDialogGenderOrStatus, tag)
                }
                R.id.tv_birthday -> {
                    //生日
                    datePicker = DatePicker(this@InputProfileActivity)
                    datePicker!!.ShowDatePick(0, "InputProfileActivity")
                }
                R.id.tv_time -> {
                    mDialogTime = DialogSelectBornTime(itemOnClick)
                    dialogShow(mDialogTime, 0)
                }
                R.id.tv_born_place -> {
                    job?.let { it.cancel() } // 协程取值未完成取消协程
                    mDialogCity = DialogSelectCity(tv_born_place.text.toString())
                    mDialogCity?.setClickListener(object : DialogSelectCity.ICityOnClick {
                        override fun onCityClick(bean: CityInfo) {
                            val str = "${bean.name}, ${bean.adminName1} \n${bean.countryName}"
                            tv_born_place?.text = str
                            map["born_place"] = str
                            tempUserBean.bornPlace = str
                            tempUserBean.cityInfo = bean
                            buttonIsEnable()
                        }
                    })
                    mDialogCity?.setOnDismissListener(DialogInterface.OnDismissListener {
                        buttonIsEnable()
                    })
                    dialogShow(mDialogCity!!, 0)
                }
                R.id.tv_status -> {
                    tag = 2
                    mDialogGenderOrStatus = DialogSelectGenderOrStatus(tag, "InputProfileActivity")
                    dialogShow(mDialogGenderOrStatus, tag)
                }
                R.id.tv_result -> {

                    val mName = edit_name.text.toString()
                    val mGender = tv_gender_1.text.toString()
                    val mBirth = tv_birthday!!.text.toString()
                    val mTime = tv_time.text.toString()
                    val mStatus = tv_status.text.toString()
                    val mPlace = tv_born_place.text.toString()

                    if (mName.isNotEmpty() &&
                        mGender.isNotEmpty() &&
                        mBirth.isNotEmpty() &&
                        mTime.isNotEmpty() &&
                        mStatus.isNotEmpty() &&
                        mPlace.isNotEmpty()
                    ) {
                        if (fromToThis.equals("AstrologyFragment")) { //匿名用户输入信息后才能跳转查看
                            mUserBean!!.name = edit_name.text.toString().trim().replace("\n", "")
                            mUserBean!!.gender = tv_gender_1.text as String
                            mUserBean!!.bornTime = tv_time.text as String
                            mUserBean!!.bornPlace = tv_born_place.text as String
                            mUserBean!!.marial_status = tv_status.text as String
                            mUserBean!!.birthday = tv_birthday!!.text as String
                            AppSettingManager.saveObject(mUserBean!!, "user_info")
                        }
                        // 在计算其他人结果页点击了计算
                        FlurryEventUtil.putDataToEvent(
                            EventType.TYPE_BIRTH_CHAT_PROFILE_CONTINUE,
                            null,
                            null
                        )
                        buildMyIntent(mName, mGender, mBirth, mTime, mStatus, mPlace)
                    }
                }
            }
        }
    }

    private fun buildMyIntent(
        mName: String,
        mGender: String,
        mBirth: String,
        mTime: String,
        mStatus: String,
        mPlace: String
    ) {
        val intent = Intent(this, BirthChatActivity::class.java)
        try {
            if (intent.getBooleanExtra("Alarm", false)) {   // 通过通知进入
                intent.putExtra("name", mName)
                intent.putExtra("gender", mGender)
                intent.putExtra("birth", mBirth)
                intent.putExtra("time", mTime)
                intent.putExtra("status", mStatus)
                intent.putExtra("place", mPlace)
                intent.putExtra("Alarm",intent.getBooleanExtra("Alarm", false))
                intent.putExtra("workName",intent.getStringExtra("workName"))
            } else {    // 正常进入
                intent.putExtra("name", mName)
                intent.putExtra("gender", mGender)
                intent.putExtra("birth", mBirth)
                intent.putExtra("time", mTime)
                intent.putExtra("status", mStatus)
                intent.putExtra("place", mPlace)
            }
            startActivity(intent)
        } catch (e: Exception) {
            intent.putExtra("name", mName)
            intent.putExtra("gender", mGender)
            intent.putExtra("birth", mBirth)
            intent.putExtra("time", mTime)
            intent.putExtra("status", mStatus)
            intent.putExtra("place", mPlace)
            startActivity(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        LiveEventBus.get("DoneInputProfileActivity", String::class.java)
            .observeSticky(this, Observer<String?> { t ->
                t?.let {
                    mDialogGenderOrStatus?.dismiss()
                    if (tag == 1) {
                        tv_gender_1.text = t
                        map["gender"] = t
                        tempUserBean.gender = t
                    } else {
                        tv_status.text = t
                        map["marial_status"] = t
                        tempUserBean.marial_status = t
                    }
                    buttonIsEnable()
                    mDialogGenderOrStatus = null
                }
            })

        LiveEventBus.get("AlertDialogDateInputProfileActivity", Bundle::class.java)
            .observeSticky(this, Observer<Bundle?> { t ->
                t?.let {
                    val year = t.getInt("year")
                    val month = t.getInt("moth")
                    val day = t.getInt("day")
//                    // 储存星座
//                    mUserBean!!.constellationName =
//                        ConstellationUtil.getStringForDate(month, day).toString()

                    // 储存生日
                    val monthTemp: String? = if (month < 10) {
                        "0$month"
                    } else {
                        month.toString()
                    }
                    val dayTemp: String? = if (day < 10) {
                        "0$day"
                    } else {
                        day.toString()

                    }
                    val mBirth = "$monthTemp-$dayTemp-$year"
//                    mUserBean!!.birthday = birthday!!

                    // sp信息更改 这里不做任何信息，等用户get result 时才存储
                    // AppSettingManager.saveUserBean(this@InputProfileActivity, mUserBean!!)
                    // 设置生日
                    tv_birthday!!.text = mBirth
                    buttonIsEnable()
                    datePicker = null
                }
            })

        buttonIsEnable()
    }

    private val itemOnClick = View.OnClickListener { v ->
        when (v?.id) {
            R.id.text_view_ok -> {
                mDialogTime?.dismiss()
                tv_time.text = mDialogTime?.getTime()
                map["time"] = mDialogTime?.getTime()
                tempUserBean.bornTime = mDialogTime?.getTime() ?: ""
                buttonIsEnable()
            }
        }
    }

    // 防止重复addFragment引发Crash
    private fun dialogShow(dialog: DialogFragment?, tag: Int) {
        if (dialog == null) return
        dialog.show(supportFragmentManager, dialog::class.java.simpleName + tag.toString())
    }

    private fun buttonIsEnable() {
        if (edit_name.text.isEmpty()
            || tv_gender_1.text.isEmpty()
            || tv_birthday!!.text.isEmpty()
            || tv_time.text.isEmpty()
            || tv_born_place.text.isEmpty()
            || tv_status.text.isEmpty()
        ) {
            tv_result.isClickable = false
            tv_result.alpha = 0.5f
        } else {
            tv_result.isClickable = true
            tv_result.alpha = 1f
        }
    }

    /**
     * RxPermission
     * https://github.com/tbruyelle/RxPermissions
     */
    @SuppressLint("CheckResult")
    private fun getLocationForPermission() {
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val rxPermissions = RxPermissions(this)
            rxPermissions.requestEach(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe { permission ->
                    if (permission.granted) {
                        job = GlobalScope.launch {
                            fusedLocationClient.lastLocation
                                .addOnSuccessListener { location: Location? ->
                                    // 得到了最后一个已知的位置。 在极少数情况下，它可以为null
                                    if (location != null) {
                                        getCityName(location)
                                        FlurryEventUtil.putDataToEvent(EventType.TYPE_LOCATION,"type","true")
                                    } else {
                                        city = null
                                        FlurryEventUtil.putDataToEvent(EventType.TYPE_LOCATION,"type","false")
                                    }
                                }
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        city = null
                    } else {
                        city = null
                    }
                }
        }
    }

    /**
     * 显示地理位置经度和纬度信息
     *
     * @param location
     */
    private fun getCityName(location: Location) {
        try {
            val geocode = Geocoder(this, Locale.getDefault())
            Observable.create(ObservableOnSubscribe<List<Address>?> { emitter ->
                emitter.onNext(geocode.getFromLocation(location.latitude, location.longitude, 1))
                emitter.onComplete()
            }).subscribeOn(Schedulers.io()) //在io执行上述操作
                .observeOn(AndroidSchedulers.mainThread()) //在UI线程执行下面操作
                .subscribe(object : io.reactivex.Observer<List<Address>?> {
                    override fun onSubscribe(d: Disposable) {}

                    override fun onNext(t: List<Address>) {
                        if (t.isNotEmpty()) {
                            city = t[0].adminArea
                            tv_born_place.text = city
                        }
                    }

                    override fun onError(e: Throwable) {}

                    override fun onComplete() {}
                })
        } catch (e: IOException) {
            Log.e("wsTest", e.toString())
        }

    }

}
